#include <ConnectionBroker/clientconnection/LongPollClientConnection.h>
#include <ConnectionBroker/server/LongPollServer.h>

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>

using namespace ConnectionBroker;

LongPollClientConnection::LongPollClientConnection(LongPollServer* pServer, boost::asio::io_service& pIoService, const int id, const std::string& pass)
: ClientConnection(), mServer(pServer), mTimer(pIoService, boost::posix_time::seconds(30)), mId(id), mPass(pass), mIoService(pIoService)
{
   //Start the timeout timer.
   mTimer.async_wait(boost::bind(&LongPollClientConnection::timeout, this, boost::asio::placeholders::error));
}

LongPollClientConnection::~LongPollClientConnection()
{
}

void LongPollClientConnection::timeout(const boost::system::error_code& pError)
{
   if(pError == boost::asio::error::operation_aborted)
   {
      mTimer.async_wait(boost::bind(&LongPollClientConnection::timeout, this, boost::asio::placeholders::error));
      return;
   }

   std::cout << this << " timed out" << std::endl;

   //The timer expired, which means we should remove this client from the list.
   mServer->longPollClientRemove(shared_from_this());
}

void LongPollClientConnection::reset()
{
   mMessages.clear();
   mTimer.expires_from_now(boost::posix_time::seconds(30));
}

void LongPollClientConnection::write(const Packet& msg)
{
   mIoService.post(boost::bind(&LongPollClientConnection::doWrite, this, msg));
}

void LongPollClientConnection::doWrite(const Packet& msg)
{
   mMessages.push_back(msg);
}

